﻿namespace CloudNinja.Metering.Tests.Provider
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    using CloudNinja.Metering.Common;
    using CloudNinja.Metering.Common.Logging;
    using CloudNinja.Metering.Data.Models;
    using CloudNinja.Metering.Providers;
    using CloudNinja.Metering.Providers.WebRole;
    using CloudNinja.Metering.Tests.Support;

    using Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling;

    using Moq;

    using Xunit;

    public class IISLogProviderTests
    {
        [Fact(Timeout = -1)]
        public void CanStartLogProviderAndPushResults()
        {
            var collectTimeInterval = TimeSpan.FromMinutes(1);

            const string ConnectionString = GlobalTestSettings.StorageConnectionString;

            var loggerMock = new Mock<ILogger>();

            var stateRepository = new Mock<IParserBookmarkRepository>();
            stateRepository.Setup(s => s.GetBookmark(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(new ParserBookmark { LastLineParsed = 1, LastTimeParsed = DateTime.UtcNow.AddDays(-10) });

            var repository = new List<MeterData>();

            var meteringRepository = new MeteringRepositoryMock(repository);

            var meteringContextMock = new Mock<IMeteringContext>();

            var retryStrategy = new Incremental();
            var retryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

            meteringContextMock.Setup(mc => mc.AzureStorageRetryPolicy).Returns(retryPolicy);

            var provider = new IISLogProvider(
                collectTimeInterval,
                ConnectionString,
                TenantIdentifierLocation.Hostheader,
                "{.*}.thecloudninja.com",
                loggerMock.Object,
                stateRepository.Object,
                meteringRepository,
                meteringContextMock.Object);

            provider.Collect();

            loggerMock.Verify(l => l.LogInformation(It.IsAny<string>()), Times.AtLeastOnce());

            Debug.WriteLine(string.Format("Parsed for {0} tenants.", repository.Count));

            Assert.True(repository.Count > 0);
        }
    }
}
